package com.example.writting.ui.articles

import android.graphics.Typeface
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.text.style.UnderlineSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.example.writting.R
import com.example.writting.data.ArgumentDataSource
import com.example.writting.data.ArticleDataSource
import com.example.writting.databinding.FragmentArticlesBinding
import com.example.writting.model.ArticleTheme
import com.example.writting.model.Argument
import com.example.writting.model.PrimaryGoal
import com.example.writting.model.SecondaryGoal
import com.google.android.material.chip.Chip

class ArticlesFragment : Fragment() {

    private var _binding: FragmentArticlesBinding? = null
    private val binding get() = _binding!!

    private var selectedTheme: ArticleTheme? = null
    private var selectedPrimaryGoal: PrimaryGoal? = null
    private var selectedSecondaryGoal: SecondaryGoal? = null
    private var selectedArguments = mutableListOf<Argument>()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentArticlesBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setupThemeDropdown()
        setupPrimaryGoalDropdown()
        setupSecondaryGoalDropdown()
    }

    private fun setupThemeDropdown() {
        val themes = ArticleDataSource.themes.map { it.name }
        val adapter = ArrayAdapter(requireContext(), android.R.layout.simple_dropdown_item_1line, themes)
        binding.themeDropdown.setAdapter(adapter)

        binding.themeDropdown.setOnItemClickListener { _, _, position, _ ->
            selectedTheme = ArticleDataSource.themes[position]
            selectedPrimaryGoal = null
            selectedSecondaryGoal = null
            selectedArguments.clear()
            updatePrimaryGoalDropdown()
            clearSecondaryGoalDropdown()
            clearContent()
            updateArgumentsChips()
        }
    }

    private fun setupPrimaryGoalDropdown() {
        binding.primaryGoalDropdown.setOnItemClickListener { _, _, position, _ ->
            selectedPrimaryGoal = selectedTheme?.primaryGoals?.get(position)
            selectedSecondaryGoal = null
            selectedArguments.clear()
            updateSecondaryGoalDropdown()
            clearContent()
            updateArgumentsChips()
        }
    }

    private fun setupSecondaryGoalDropdown() {
        binding.secondaryGoalDropdown.setOnItemClickListener { _, _, position, _ ->
            selectedSecondaryGoal = selectedPrimaryGoal?.secondaryGoals?.get(position)
            selectedArguments.clear()
            updateContent()
            updateArgumentsChips()
        }
    }

    private fun updatePrimaryGoalDropdown() {
        val primaryGoals = selectedTheme?.primaryGoals?.map { it.name } ?: emptyList()
        val adapter = ArrayAdapter(requireContext(), android.R.layout.simple_dropdown_item_1line, primaryGoals)
        binding.primaryGoalDropdown.setAdapter(adapter)
        binding.primaryGoalDropdown.setText("", false)
    }

    private fun updateSecondaryGoalDropdown() {
        val secondaryGoals = selectedPrimaryGoal?.secondaryGoals?.map { it.name } ?: emptyList()
        val adapter = ArrayAdapter(requireContext(), android.R.layout.simple_dropdown_item_1line, secondaryGoals)
        binding.secondaryGoalDropdown.setAdapter(adapter)
        binding.secondaryGoalDropdown.setText("", false)
    }

    private fun clearSecondaryGoalDropdown() {
        binding.secondaryGoalDropdown.setText("", false)
    }

    private fun clearContent() {
        binding.openingParagraphText.text = ""
        binding.closingParagraphText.text = ""
        binding.argumentsText.text = ""
    }

    private fun updateContent() {
        selectedSecondaryGoal?.let { goal ->
            val openingParagraph = "        " + goal.openingParagraph
                .replace("{二级目标}", goal.name)
                .replace("{一级目标}", selectedPrimaryGoal?.name ?: "")
                .replace("{主题}", selectedTheme?.name ?: "")
            val closingParagraph = "        " + goal.closingParagraph
                .replace("{二级目标}", goal.name)
                .replace("{一级目标}", selectedPrimaryGoal?.name ?: "")
                .replace("{主题}", selectedTheme?.name ?: "")

            binding.openingParagraphText.text = openingParagraph
            binding.closingParagraphText.text = closingParagraph
        }
    }

    private fun updateArgumentsChips() {
        binding.argumentsChipGroup.removeAllViews()
        binding.argumentsText.text = ""

        val secondaryGoalName = selectedSecondaryGoal?.name ?: return
        val availableArguments = ArgumentDataSource.arguments.filter { argument ->
            argument.replacements.containsKey(secondaryGoalName)
        }

        availableArguments.forEach { argument ->
            val chip = Chip(requireContext()).apply {
                text = argument.name
                isClickable = true
                isCheckable = false
                setOnClickListener {
                    addArgument(argument)
                }
            }
            binding.argumentsChipGroup.addView(chip)
        }
    }

    private fun addArgument(argument: Argument) {
        val secondaryGoalName = selectedSecondaryGoal?.name ?: return
        val primaryGoalName = selectedPrimaryGoal?.name ?: return
        val themeName = selectedTheme?.name ?: return
        val replacements = argument.replacements[secondaryGoalName] ?: return

        var text = argument.template
            .replace("{主题}", themeName)
            .replace("{二级目标}", secondaryGoalName)
            .replace("{一级目标}", primaryGoalName)

        // 按顺序替换所有{目标替换}
        var currentText = text
        replacements.forEach { replacement ->
            currentText = currentText.replaceFirst("{目标替换}", replacement)
        }
        text = currentText

        // 处理段落缩进
        text = text.split("\n").joinToString("\n") { line ->
            if (line.isNotBlank()) "       $line" else line
        }

        val spannable = SpannableStringBuilder(text)

        // 设置主题、二级目标和一级目标的样式
        val oliveColor = ContextCompat.getColor(requireContext(), R.color.olive)
        listOf(themeName, secondaryGoalName, primaryGoalName).forEach { target ->
            var startIndex = text.indexOf(target)
            while (startIndex != -1) {
                // 确保是完整的匹配，而不是部分匹配
                val endIndex = startIndex + target.length
                if (endIndex <= text.length && 
                    (startIndex == 0 || !text[startIndex - 1].isLetterOrDigit()) &&
                    (endIndex == text.length || !text[endIndex].isLetterOrDigit())) {
                    spannable.setSpan(
                        ForegroundColorSpan(oliveColor),
                        startIndex,
                        endIndex,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                    spannable.setSpan(
                        StyleSpan(Typeface.BOLD),
                        startIndex,
                        endIndex,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                }
                startIndex = text.indexOf(target, startIndex + 1)
            }
        }

        // 设置所有替换内容的样式（下划线）
        replacements.forEach { replacement ->
            if (replacement.isNotEmpty()) {
                var startIndex = text.indexOf(replacement)
                while (startIndex != -1) {
                    // 确保是完整的匹配，而不是部分匹配
                    val endIndex = startIndex + replacement.length
                    if (endIndex <= text.length && 
                        (startIndex == 0 || !text[startIndex - 1].isLetterOrDigit()) &&
                        (endIndex == text.length || !text[endIndex].isLetterOrDigit())) {
                        spannable.setSpan(
                            UnderlineSpan(),
                            startIndex,
                            endIndex,
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                    }
                    startIndex = text.indexOf(replacement, startIndex + 1)
                }
            }
        }

        val currentArgumentsText = binding.argumentsText.text.toString()
        if (currentArgumentsText.isNotEmpty()) {
            binding.argumentsText.append("\n\n")
        }
        binding.argumentsText.append(spannable)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 